package com.myapp.config;

import com.gitee.fastmybatis.core.query.TenantQuery;
import com.myapp.context.TenantContext;
import com.myapp.interceptor.TenantInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author thc
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    static {
        // 设置多租户id数据库字段，不设置默认：tenant_id
        TenantQuery.setDefaultTenantColumnName("tenant_id");
        // 添加多租户条件，每次new TenantQuery()时都会触发下面这段代码
        TenantQuery.setDefaultTenantQueryListener(query -> {
            String tenantId = TenantContext.getTenantId();
            if (StringUtils.hasText(tenantId)) {
                query.eq(query.getTenantColumnName(), tenantId);
            } else {
                // 【可选】如果没有传tenantId，则添加一个 1=2 条件，从而查不到数据
                query.oneEqTwo();
            }
        });
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TenantInterceptor());
    }
}
